/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cn.lotary.base.web;

import com.cn.lotary.base.dao.AbstractEntity;
import com.cn.lotary.util.LoggerUtils;
import com.cn.lotary.util.MessageBundle;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.persistence.metamodel.SingularAttribute;

/**
 * in testing
 *
 * @author user192
 */
public class ForeignConverter<T extends AbstractEntity> implements Converter {

    private SingularAttribute foreignField;
    private BaseController<T> baseController;

    public ForeignConverter(SingularAttribute foreignField, BaseController<T> baseController) {
        this.foreignField = foreignField;
        this.baseController = baseController;
    }

    @Override
    public T getAsObject(FacesContext context, UIComponent toValidate, String value) {
        //TODO: 校验 value
        Object foreginEntity = null;
        String viewId = toValidate.getId();
        if (baseController.verificationId(viewId) || value == null || "".equals(value)) {
            return null;
        }

        try {
            Class<?> entityClass = baseController.getEntity().getClass();
            String field = baseController.getIdByViewId(viewId);
            Field declaredField = entityClass.getDeclaredField(field);
            Class<?> foreignClass = declaredField.getType();
            Method method = entityClass.getMethod(baseController.getSetForegin(field), foreignClass);
            foreginEntity = baseController.dao().findByColumnAndEntityClass(foreignClass, foreignField.getName(), value);

            if (foreginEntity != null) {
                method.invoke(baseController.getEntity(), foreginEntity);
            } else {
                MessageBundle.validatorMessage(FacesMessage.SEVERITY_WARN,
                        toValidate,
                        context, value.toString(),
                        MessageBundle.DOES_NOT_EXIST);
            }
        } catch (Exception e) {
            LoggerUtils.error(e);
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent toValidate, Object value) {
        //TODO： 通过反射取值
        return value.toString();
    }
}
